<template>
    <div>
        <input type="text" placeholder="请输入关键字" v-model="keyword">
        <button @click="btnget()">查找</button>
        <button @click="btnAll()">新增</button>
    </div>
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>书名</th>
                <th>作者</th>
                <th>简介</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="(item,index) in booksList" :key="item.id">
                <td>{{ index+1 }}</td>
                <td>{{ item.booksName }}</td>
                <td>{{ item.author }}</td>
                <td>{{ item.shortDes }}</td>
                <td>
                    <input @click="editBook(item.id)" type="button" value="编辑">
                    <input @click="deleteBook(item.id)" type="button" value="删除">
                </td>
            </tr>
        </tbody>
    </table>
</template>

<script setup>
import {onMounted,reactive,ref} from 'vue';
import{ useRouter} from 'vue-router'
import { getAll,delbooks } from '@/api/booksApi';


const booksList= ref([])
const router = useRouter();


let keyword =ref('')

async function btnget() {
    let res =await getAll (keyword.value)
    booksList.value.splice(0)
    booksList.value=res.data
}


function btnAll(){
    router.push('about')
}
function editBook(id){
    router.push('/books/:id')
}
function deleteBook(id) {
  console.log('删除')
  if (confirm('确认删除吗?')) {
    delbooks(id)
    let idx = booksList.value.findIndex((item) => item.id == id)
    console.log(idx)

    booksList.value.splice(idx, 1)
  }
}

onMounted(async ()=>{
    let res =await getAll()
    booksList.value=res.data
})



</script>